package com.letfox.common.util.http;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;

import com.letfox.common.enums.CharsetEnum;


/**
 * ResponseUtils
 */
public final class HTTPResponseUtil {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(HTTPResponseUtil.class);

    private static final String DEFAULT_CHARSET = CharsetEnum.UTF_8.value;

    /**
     * 发送文本。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text 发送的字符串
     */
    public static void renderText(HttpServletResponse response, String text) {
        render(response, "text/plain;charset=" + DEFAULT_CHARSET, text);
    }

    /**
     * 发送json。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text 发送的字符串
     */
    public static void renderJson(HttpServletResponse response, String text) {
        render(response, "application/json;charset=" + DEFAULT_CHARSET, text);
    }

    /**
     * 发送xml。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text 发送的字符串
     */
    public static void renderXml(HttpServletResponse response, String text) {
        render(response, "text/xml;charset=" + DEFAULT_CHARSET, text);
    }

    /**
     * 发送xml。使用UTF-8编码。
     *
     * @param response HttpServletResponse
     * @param text 发送的字符串
     */
    public static void renderXmlWithEncode(HttpServletResponse response, String encode, String text) {
        render(response, "text/xml;charset=" + encode, text);
    }

    /**
     * 发送内容。使用UTF-8编码。
     *
     * @param response
     * @param contentType
     * @param text
     */
    public static void render(HttpServletResponse response, String contentType, String text) {
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(text);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
